package com.huitone.smspfm.oldclient.asclient.send;

import java.util.Date;
import java.util.Iterator;
import java.util.Map.Entry;

import com.bin.common.utils.DateTimeUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.context.app.AppManager;
import com.huitone.smspfm.oldclient.app.AppStaticConfigs;
import com.huitone.smspfm.oldclient.logger.ExtLogger;
import com.huitone.smspfm.oldclient.model.MtGroup;
import com.huitone.smspfm.oldclient.model.MtSms;
import com.huitone.smspfm.oldclient.store.MtGroupTmpStore;
import com.huitone.smspfm.oldclient.store.MtTmpStore;
import com.huitone.smspfm.socket.client.SocketClient;
import com.huitone.smspfm.socket.protocol.sgip.constant.CommandID;
import com.huitone.smspfm.socket.protocol.sgip.constant.Constant;
import com.huitone.smspfm.socket.protocol.sgip.message.Message;
import com.huitone.smspfm.socket.protocol.sgip.message.msgbody.Submit2;
import com.huitone.smspfm.socket.protocol.sgip.message.msghead.Head;
import com.huitone.smspfm.socket.utils.SerialUtils;


/**   
* @Title: SendMsgThread.java 
* @Package com.unicom.gddw.oldplatform 
* @Description: TODO 用于定时检查未成功合并的长短信此时是否能够合并数据并发送
* @author ybliang   
* @date 2017年3月9日 下午3:21:40 
* @version V1.0   
*/
public class SendCrossFileMsgOldManager extends Thread {
	
	private final static ExtLogger logger = ExtLogger.create(SendCrossFileMsgOldManager.class);

	private static SendCrossFileMsgOldManager instance = new SendCrossFileMsgOldManager();
	
	private long sleepTime = 1000;
	private long failIntevel = 600000;
	
	public static SendCrossFileMsgOldManager getInstance() {
		return instance;
	}
	
	private SendCrossFileMsgOldManager() {}

	@Override
	public void run() {
		
		logger.info("启动跨文件长短信合并发送线程。");
		
		while(AppManager.isRunning() && !this.isInterrupted()) {
			
			Iterator<Entry<String, MtGroup>> iterator = MtGroupTmpStore.get().entrySet().iterator();
			
			while(iterator.hasNext() && AppManager.isRunning() && !this.isInterrupted()) {
				
				Entry<String, MtGroup> entry = iterator.next();
				
				MtGroup mtGroup = entry.getValue();
				
				if (mtGroup == null) {
					continue;
				}
				
				if (mtGroup.sendAble()) {
					
					MtSms mtSms = mtGroup.merged();
					try {
					
						String serviceCode = AppStaticConfigs.serviceCode;
						if (AppStaticConfigs.isUseOldServiceCode) {
							serviceCode = mtSms.getServiceCode();
						}
						
						Submit2 submit = Submit2.build(mtSms.getMobileno(), AppStaticConfigs.srvNode, serviceCode, 
								mtSms.getSendport(), 1, Constant.MessageCodingE.GBK.getValue(), 
								Constant.MessageTypeE.SMS.getValue(), mtSms.getContent(), mtSms.getClientname(), mtSms.getOldserialnos());
						Head head = Head.build(submit.length(), CommandID.SGIP_SUBMIT2, AppStaticConfigs.codeRule, StringUtils.toIntegerP(DateTimeUtils.dateToStr(new Date(), "MMddHHmmss")), SerialUtils.getSerial());
						
						String serialNo = head.getSerialNo();
						
						mtSms.setSerialno(serialNo);
						mtSms.setSrvNode(AppStaticConfigs.srvNode);
						mtSms.setServiceCode(serviceCode);
						mtSms.setReportflag(1);
						mtSms.setCoderule(head.getSerialNoPart1());
						mtSms.setDatetime(head.getSerialNoPart2());
						mtSms.setSeqnumber(head.getSerialNoPart3());
						mtSms.setiSendTimes(1);
						mtSms.setLastSendTime(new Date());
						
						MtTmpStore.put(serialNo, mtSms);
						
						MtGroupTmpStore.remove(mtGroup.getGroupKey());
					
						boolean status = SocketClient.getInstance().sendMsg(head, submit);
						
						logger.submit(new Message(head, submit).toString() + " status:" + status);
						
					} catch (Exception e) {
						logger.error("跨文件长短信发送时报错:" + mtSms.toString(), e);
					}
				} else {
					long currTime = System.currentTimeMillis();
					if (currTime - mtGroup.getLastAddTime().getTime() >= failIntevel) {
						// 超时没有组装完整则默认失败
						StringBuffer buffer = new StringBuffer();
						Iterator<Entry<Integer, MtSms>> items = mtGroup.getItems().entrySet().iterator();
						while(items.hasNext()) {
							buffer.append("\n");
							buffer.append(items.next().getValue().toString());
						}
						logger.warn("长短信等待组装时间超时,已读取长短信分段如下:" + buffer.toString());
						
						MtGroupTmpStore.remove(mtGroup.getGroupKey());
					}
				}
			}
			
			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				break;
			}
		}
		
		logger.info("跨文件长短信发送线程退出。");
	}

	public void shutdown() {
		
	}
}
